<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    append-to-body
    :close-on-click-modal="false"
    @close="closeDialog()"
    :visible="visible"
    width="600px"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      label-width="100px"
    >
      <el-form-item label="二维码名称" prop="qrcodeName">
        <el-input
          v-model="dataForm.qrcodeName"
          placeholder="请输入二维码名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="有效期" prop="qrcodeValidType">
        <el-select
          v-model="dataForm.qrcodeValidType"
          filterable
          placeholder="请选择有效期"
          clearable
          size="small"
          class="margin-left-xs"
          style="width:100%"
        >
          <el-option
            v-for="dict in qrcodeValidTypeList"
            :key="dict.value"
            :label="dict.text"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="时间区间" prop="dateTimeRange" v-if="dataForm.qrcodeValidType == qrcodeValidTypeEnum.timeSpan">
        <el-date-picker
          v-model="dataForm.dateTimeRange"
          style="width:100%"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          value-format="yyyy-MM-dd"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="二维码类型" prop="qrcodeType">
        <el-select
          v-model="dataForm.qrcodeType"
          filterable
          placeholder="请选择二维码类型"
          clearable
          size="small"
          class="margin-left-xs"
          style="width:100%"
        >
          <el-option
            v-for="dict in qrcodeTypeList"
            :key="dict.value"
            :label="dict.text"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="二维码前缀" prop="prefix">
        <el-input
          v-model="dataForm.prefix"
          placeholder="请输入二维码前缀"
        ></el-input>
      </el-form-item>

      <el-form-item label="跳转位置" prop="navType">
        <el-select
          v-model="dataForm.navType"
          filterable
          placeholder="请选择跳转位置"
          clearable
          size="small"
          class="margin-left-xs"
          style="width:100%"
          @change="handleNavTypeChange()"
        >
          <el-option
            v-for="dict in navTypeList"
            :key="dict.value"
            :label="dict.text"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <template v-if="dataForm.navType">
        <el-row v-if="dataForm.navType == navTypeEnum.sku">
          <el-form-item label="商品" prop="spuId">
            <el-select
              v-model="dataForm.spuId"
              filterable
              placeholder="请选择商品"
              clearable
              size="small"
              class="margin-left-xs"
              style="width:100%"
              @change="handleSpuChange()"
            >
              <el-option
                v-for="dict in goodsSpuList"
                :key="dict.id"
                :label="dict.spuTitle"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="商品sku" prop="skuId">
            <el-select
              v-model="dataForm.skuId"
              filterable
              placeholder="请选择商品sku"
              clearable
              size="small"
              class="margin-left-xs"
              style="width:100%"
            >
              <el-option
                v-for="dict in goodsSkuList"
                :key="dict.id"
                :label="dict.skuName"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-row>

        <el-row v-if="dataForm.navType == navTypeEnum.topicPage">
          <el-form-item label="专题页" prop="targetTopicPageId">
            <el-select
              v-model="dataForm.targetTopicPageId"
              filterable
              placeholder="请选择专题页"
              clearable
              size="small"
              class="margin-left-xs"
              style="width:100%"
            >
              <el-option
                v-for="dict in topicPageList"
                :key="dict.id"
                :label="dict.topicName"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-row>

      </template>

      <el-form-item label="上架状态:" prop="status">
        <el-radio-group v-model="dataForm.status">
          <el-radio label="1" border>上架</el-radio>
          <el-radio label="0" border>下架</el-radio>
        </el-radio-group>
      </el-form-item>


    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" v-if="canSubmit"
        >确定</el-button
      >
    </span>
  </el-dialog>
</template>

<script>
import { getObj, addObj, putObj } from "@/api/shop_operate/qrcode/qrcode";
import {qrcodeValidTypeEnum, qrcodeTypeEnum, baseUrlEnum, navTypeList, navTypeEnum} from '@/const/const'
import {getGoodsSpuList} from '@/api/shop_goods/spu';
import {getGoodsSkuBySpuId} from '@/api/shop_goods/sku';
import {getTopicPageList} from '@/api/shop_operate/topic/topic';

export default {
  props:{
    visible: {
      type: Boolean,
      default: false
    },
  },
  data(){
    return{
      // 二维码基地址
      baseUrlEnum,
      // 二维码有效期
      qrcodeValidTypeEnum, 
      // 二维码类型
      qrcodeTypeEnum,
      // 跳转位置列表
      navTypeList,
      // 跳转枚举
      navTypeEnum,
      canSubmit: false,
      loading:false,
      dataForm:{
        dateTimeRange:[],
        status:'1',
      },
      dataRule:{
        qrcodeName: [
          { required: true, message: "二维码名称不能为空", trigger: "blur" },
        ],
        qrcodeValidType: [
          { required: true, message: "有效期不能为空", trigger: "blur" },
        ],
        dateTimeRange: [
          { required: true, message: "时间区间不能为空", trigger: "blur" },
        ],
        qrcodeType: [
          { required: true, message: "二维码类型不能为空", trigger: "blur" },
        ],
        navType: [
          { required: true, message: "跳转位置不能为空", trigger: "blur" },
        ],
        status: [
          { required: true, message: "上架状态不能为空", trigger: "blur" },
        ],
        spuId: [
          { required: true, message: "商品不能为空", trigger: "blur" },
        ],
        skuId: [
          { required: true, message: "商品Sku不能为空", trigger: "blur" },
        ],
        targetTopicPageId: [
          { required: true, message: "专题页不能为空", trigger: "blur" },
        ]
      },

      // 商品列表
      goodsSpuList:[],
      // 商品sku列表
      goodsSkuList:[],
      // 专题页列表
      topicPageList:[],

      qrcodeValidTypeList:[{
        value:qrcodeValidTypeEnum.none,
        text:'无限制'
      },{
        value:qrcodeValidTypeEnum.timeSpan,
        text:'时间区间'
      }],

      qrcodeTypeList:[{
        value:qrcodeTypeEnum.scanCash,
        text:'扫码红包'
      }],

    }
  },
  methods:{

    /**
     * 初始化
     */
    init(id){
      this.canSubmit = true
      // 获取商品列表
      this.getGoodsSpuList()
      // 获取专题页信息
      this.getTopicPageList();

      if(id){
        getObj(id).then((response) => {
          let data = response.data.data;
          // 格式化时间区间
          if(data.startDate && data.endDate){
            this.$set(data, 'dateTimeRange', [])
            data.dateTimeRange.push(this.dayjs(data.startDate).format('YYYY-MM-DD'))
            data.dateTimeRange.push(this.dayjs(data.endDate).format('YYYY-MM-DD'))
          }
          this.dataForm = data
          if(this.dataForm.spuId){
            // 获取商品skuId
            this.getGoodsSkuBySpuId()
          }
        });
      }
    },

    /**
     * 跳转位置选择
     */
     handleNavTypeChange(){
      this.dataForm.spuId = null
      this.dataForm.skuId = null
      this.dataForm.targetTopicPageId = null
    },

    /**
     * 商品选择
     */
     handleSpuChange(){
      this.dataForm.skuId = null
      this.getGoodsSkuBySpuId()
    },

    /**
     * 获取所有的商品spu
     */
     getGoodsSpuList(){
      getGoodsSpuList().then(res=>{
        this.goodsSpuList = res.data.data
      })
    },

    /**
     * 获取专题页信息
     */
     getTopicPageList(){
      getTopicPageList().then(res=>{
        this.topicPageList = res.data.data
      })
    },

    /**
     * 根据spuId获取sku列表
     */
     getGoodsSkuBySpuId(){
      debugger
      if(this.dataForm.spuId){
        this.loading = true
        getGoodsSkuBySpuId({spuId:this.dataForm.spuId}).then(res=>{
          this.loading = false
          this.goodsSkuList = res.data.data
        })
      } else {
        this.goodsSkuList = []
      }
    },

    /**
     * 提交
     */
    dataFormSubmit(){
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.canSubmit = false;
          let submitData = JSON.parse(JSON.stringify(this.dataForm))

          // 时间区间
          if(submitData.dateTimeRange && submitData.dateTimeRange.length > 0 && submitData.qrcodeValidType == qrcodeValidTypeEnum.timeSpan){
            submitData.startDate = submitData.dateTimeRange[0] + " 00:00:00"
            submitData.endDate = submitData.dateTimeRange[1] + " 23:59:59"
          } else {
            submitData.startDate = null
            submitData.endDate = null
          }

          submitData.qrcodeBaseUrl = baseUrlEnum.qrcode

          if (submitData.id) {
            putObj(submitData)
              .then((data) => {
                this.$notify.success("修改成功");
                this.$emit("refreshDataList");
                this.closeDialog()
              }).catch(() => {
                this.canSubmit = true;
              });
          } else {
            addObj(submitData)
              .then((data) => {
                this.$notify.success("添加成功");
                this.$emit("refreshDataList");
                this.closeDialog()
              }).catch(() => {
                this.canSubmit = true;
              });
          }

        }
      })
    },

    indexMethod(index) {
      return (
        (this.queryParams.pageIndex - 1) * this.queryParams.pageSize + index + 1
      );
    },

    //重置表单
    closeDialog() {
      this.$emit('update:visible', false)
    },
  }
}
</script>
